package cn.sytton.taffe.wx.service.impl;

import cn.sytton.taffe.auth.entity.AuthUserEntity;
import cn.sytton.taffe.auth.mapper.SecurityMapper;
import cn.sytton.taffe.auth.service.ILoginService;
import cn.sytton.taffe.auth.service.security.UserDetailFactory;
import cn.sytton.taffe.framework.exception.BizException;
import cn.sytton.taffe.framework.security.entity.LoginUser;
import cn.sytton.taffe.framework.security.user.UserAuthenticationToken;
import cn.sytton.taffe.wx.entity.WeixinUserEntity;
import cn.sytton.taffe.wx.helper.JsCode2session;
import cn.sytton.taffe.wx.mapper.WeixinUserMapper;
import cn.sytton.taffe.wx.service.IWxAuthService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Objects;

/**
 * 微信登录服务层实现类
 *
 * @author skyrock
 */
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class WxAuthService implements IWxAuthService {

    @Resource
    private JsCode2session jsCode2session;
    @Resource
    private WeixinUserMapper weixinUserMapper;
    @Resource
    private SecurityMapper securityMapper;
    @Resource
    private AuthenticationManager authenticationManager;
    @Resource
    private UserDetailFactory userDetailFactory;
    @Resource
    private ILoginService loginService;

    @Override
    public WeixinUserEntity loginByWxCode(String code) {
        Map<String, Object> result = jsCode2session.getOpenId(code);
        if (Objects.nonNull(result) && result.containsKey("openid")) {
            String openId = result.get("openid").toString();
            WeixinUserEntity wxUser = weixinUserMapper.selectById(openId);
            if (Objects.nonNull(wxUser) && StringUtils.hasText(wxUser.getUserId())) {
                AuthUserEntity authUser = securityMapper.findUserById(wxUser.getUserId());
                if (Objects.nonNull(authUser)) {
                    LoginUser loginUser = userDetailFactory.create(authUser.getLoginName(), authUser);
                    Authentication authentication =  authenticationManager.authenticate(new UserAuthenticationToken(loginUser));
                    String token = loginService.generateToken(authentication);
                    wxUser.setToken(token);
                    return wxUser;
                } else {
                    log.info("绑定用户openId=["+openId+"],userId=["+wxUser.getUserId()+"]错误");
                    return wxUser;
                }
            } else {
                //未绑定
                log.info("未绑定openId=["+openId+"]");
                return wxUser;
            }
        } else {
            throw new BizException("参数code["+code+"]错误");
        }
    }
}
